//
//  UITextField+ADUtil.m
//  ADKit
//
//  Created by duzexu on 2017/12/1.
//  Copyright © 2017年 duzexu. All rights reserved.
//

#import "UITextField+ADUtil.h"
#import "ADKitHeaders.h"

static char AD_UITextField_ContentInsets;

@implementation UITextField (ADUtil)

+ (void)load {
    [self swizzleInstanceMethod:@selector(drawTextInRect:) with:@selector(ad_drawTextInRect:)];
    [self swizzleInstanceMethod:@selector(drawPlaceholderInRect:) with:@selector(ad_drawPlaceholderInRect:)];
}

- (void)ad_drawTextInRect:(CGRect)rect {
    return [self ad_drawTextInRect:UIEdgeInsetsInsetRect(rect, self.contentInsets)];
}

- (void)ad_drawPlaceholderInRect:(CGRect)rect {
    return [self ad_drawPlaceholderInRect:UIEdgeInsetsInsetRect(rect, self.contentInsets)];
}

- (void)setContentInsets:(UIEdgeInsets)contentInsets {
    [self setValue:@(contentInsets.top) forKey:@"paddingTop"];
    [self setValue:@(contentInsets.left) forKey:@"paddingLeft"];
    [self setValue:@(contentInsets.bottom) forKey:@"paddingBottom"];
    [self setValue:@(contentInsets.right) forKey:@"paddingRight"];
    [self setAssociateValue:[NSValue valueWithUIEdgeInsets:contentInsets] withKey:&AD_UITextField_ContentInsets];
}

- (UIEdgeInsets)contentInsets {
    return [[self getAssociatedValueForKey:&AD_UITextField_ContentInsets] UIEdgeInsetsValue];
}

- (void)ad_limitMaxLength:(NSInteger)maxLength {
    @weakify(self);
    [[[RACSignal merge:@[RACObserve(self, text),self.rac_textSignal]] skip:0] subscribeNext:^(NSString * text) {
        @strongify(self);
        UITextRange *selectedRange = [self markedTextRange];
        UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制,防止中文被截断
        if (position) return ;
        if (text.length <= maxLength) return;
        
        //中文和emoj表情存在问题，需要对此进行处理
        NSRange range;
        NSUInteger inputLength = 0;
        for(int i =0 ; i < text.length && inputLength <= maxLength; i += range.length){
            range = [self.text rangeOfComposedCharacterSequenceAtIndex:i];
            inputLength += [text substringWithRange:range].length;
            if (inputLength > maxLength) self.text = [text substringWithRange:NSMakeRange(0, range.location)];
        }
    }];
}

@end

@implementation UITextField (ADLocalized)

- (void)setLocalized_text:(NSString *)localized_text {
    self.text = localized_text.ad_localized;
}

- (void)setLocalized_placeholder:(NSString *)localized_placeholder {
    self.placeholder = localized_placeholder.ad_localized;
}

@end
